const express = require("express");
const SocketServer = require("ws").Server;

const PORT = 8001;

const server = express().listen(PORT, () =>
    console.log(`SocketServer Listening on http://localhost:${PORT}`)
);

// 将 express 服务交给 socketServer 开启 webSocket 服务
const wss = new SocketServer({ server });

wss.on("connection", (ws) => {
    console.log("Client connected");
    // console.log('wss::', wss)
    // console.log('wss.clients::', wss.clients) // wss.clients is a set
    ws.on("message", (message) => {
        console.log(
            "服务端收到: %s",
            message,
            typeof message,
            message.toString()
        );
        // ws.send(message) // 直接返回收到的消息
        // ws.send(message.toString().split('').reverse().join('')) // 返回 翻转的消息
        sendToOthers(ws, message);
    });

    ws.on("close", () => console.log("Client disconnected"));

    ws.send("welcome");
});

// 用浏览器打开两个页面进行测试 打开链接可以是下面随便一个
// 1. http://localhost:9000?port=8001
// 2. http://localhost:9000/chat
function sendToOthers(ws, msg) {
    wss.clients.forEach((client) => {
        if (client !== ws && client.readyState === ws.OPEN) {
            client.send(msg);
        }
    });
}
